import { Card, Form, Input, Button, Select, Table, Space, Tag ,message} from "antd";
import React, { useEffect, useState } from "react";
import { SearchOutlined } from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import { useNavigate,Location } from 'react-router-dom'
import { reqHospitalList ,reqGetProvinceList, reqGetCityOrDistrictList,reqHospitalChangeStatus} from "@api/user/hospital/hospitalList";
import {
  IhospitalListParams,
  IhospitalListResItem,
  IhospitalList,
  ProvinceList,
  IhospitalListResponse
} from "@/api/user/hospital/model/hospitalListTypes";

// import Loading from "@/components/Loading";
const { Option } = Select;
 




function HospitalList() {
  let isSearch = false
  const onFinish = () => {
    isSearch = true //标记一下,后面再发请求,要带筛选条件
    getHospitalList(1, pageSize)
  };
 

  const [form]=Form.useForm()
  const navigate = useNavigate()
  const [page, setpage] = useState(1);
  const [pageSize, setpageSize] = useState(2);
  const [total, setTotal] = useState(50);
  const [hospitalList, setHospitalList] = useState<IhospitalList>([]);
  // const onFinishFailed = (errorInfo: any) => {
  //   console.log('Failed:', errorInfo);
  // };
 // 定义省市区数据
 const [ProvinceList,setProvinceList]=useState<ProvinceList>([])
 const [city, setCity] = useState<ProvinceList>([])
const [district, setDistrict]=useState<ProvinceList>([])
 // 医院等级
 const [hospitalOrder, sethospitalOrder] = useState<ProvinceList>([])


const change=(id:string,status:0|1)=>{
  return (
    async ()=>{
      await reqHospitalChangeStatus(id,status)
      message.success("更新状态成功");
      getHospitalList( page, pageSize );
    }
  )
}



 

 
 const columns: ColumnsType<IhospitalListResItem> = [
  {
    title: "序号",
    dataIndex: "name",
    
    render: (text,record,index) =>index+1
  },
  {
    title: "医院logo",
    render:(data)=>{
      return (
        <img src={'data:image/png;base64,' + data.logoData} alt="" width="80" />
      )
    }
  
  },
  {
    title: '医院名称',
   dataIndex:'hospname'
   
  },
  {
    title:  '等级',
    key: "tags",
   
    render(data) {
      return data.param.hostypeString
    },
  },
  {
    title: '详细地址',
    
    render:(data)=>{
      return data.param.fullAddress
    }
  },
  {
    title: '状态',
    render(data) {
      return data.status ? '已上线' : '未上线'
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '操作',

    render: (data) => (
      <Space size="middle">
        <Button type="primary"   onClick={() => {
              navigate('/syt/hospital/hospitalList/show', {
                state: data.id,
              })
            }} >查看</Button>
        <Button onClick={() => {
              navigate(`/syt/hospital/hospitalList/schedule/${data.hoscode}`)
            }}
        type="primary">排班</Button>
         {data.status===0? <Button type="primary" onClick={change(data.id,1)} >上线</Button>



         : <Button type="primary"  onClick={change(data.id,0)}  >下线</Button>
        }


      </Space>
    ),
  },
  
];

const onClear = () => {
   
  isSearch = false //标记一下,后面再发请求,不要带筛选条件
  // 清空表单的选项
  form.resetFields()

  
  setCity([])
  setDistrict([])

  getHospitalList(1, pageSize)
  console.log(123)
}






  useEffect(() => {
   

    getHospitalList( page, pageSize );
    getProvinceList()
        // 获取医院等级数据
    getHospitalOrder()
  }, []);

  async function getHospitalList(page: number, limit: number) {
    setpage(page)
    setpageSize(limit)
    let result: IhospitalListResponse
      if(isSearch){
       
        const {
          hosname,
          hoscode,
          hostype,
          provinceCode,
          cityCode,
          districtCode,
          status,
        } = form.getFieldsValue()

        console.log(hosname,
          hoscode,
          hostype,
          provinceCode,
          cityCode,
          districtCode,
          status,)

        result = await reqHospitalList({
          page,
          limit,
          hosname,
          hoscode,
          hostype,
          provinceCode,
          cityCode,
          districtCode,
          status,
        })
       

      }
      else{
         result = await reqHospitalList({page,limit});
      }
    

    
    setTotal(result.totalElements);
   setHospitalList(result.content);
   console.log(result.content)
  }
 
   // 获取省数据的方法
  const getProvinceList = async () => {
    form.setFieldsValue({cityCode:undefined,districtCode:undefined})
    const res = await reqGetProvinceList();
    setProvinceList(res);
  };

  async function getCity(provinceId:string){
    console.log('hahaha')
      form.setFieldsValue({distritCode:undefined,cityCode: undefined,})
      const result =await reqGetCityOrDistrictList(provinceId)
      setCity(result)
  }

  async function getDistrict(cityId:string){
    form.setFieldsValue({ districtCode: undefined })
    const result =await reqGetCityOrDistrictList(cityId)
    setDistrict(result)
}


async function getHospitalOrder() {
  const result = await reqGetCityOrDistrictList('10000')
  sethospitalOrder(result)
}




  return (
    <Card>
      <Form layout="inline"  onFinish={onFinish}  form={form}  >
        <Form.Item  name="provinceCode">
          <Select style={{ width: 200 }} placeholder="请选择省"
           
           onChange={getCity}>
           {ProvinceList.map((item:any)=>{
            return (   
               <Option value={item.value} key={item.id}>
               {item.name}
            </Option>  
              )
           })

           }

           
            
          </Select>
        </Form.Item>

        <Form.Item name="cityCode">
          <Select style={{ width: 200 }} placeholder="请选择市"
            onChange={getDistrict}
          >
            {city.map((item)=>{
              return <Option key={item.id} value={item.value}>{item.name}</Option>
            })}
            
          </Select>
        </Form.Item>

        <Form.Item name="districtCode">
          <Select style={{ width: 200 }} placeholder="请选择区">
            {district.map((item)=>{
              return <Option key={item.id}  value={item.value}>{item.name}</Option>
            })}
            
          </Select>
        </Form.Item>

        <Form.Item name="hosname">
          <Input placeholder="医院名称"></Input>
        </Form.Item>

        <Form.Item name="hoscode">
          <Input
            style={{ width: 200,}}
            placeholder="医院编码"
          ></Input>
        </Form.Item>

        <Form.Item name="hostype">
          <Select style={{ width: 200, marginTop: 10  }} placeholder="医院类型">
           {hospitalOrder.map((item)=>{
            return  <Option key={item.id}  value={item.value}>{item.name}</Option>
           })}
           
          </Select>
        </Form.Item>

        <Form.Item name="status">
          <Select style={{ width: 200, marginTop: 10 }} placeholder="医院状态">
            <Option value={0}>未上线</Option>
            <Option value={1}>已上线</Option>
          </Select>
        </Form.Item>

        <Form.Item>
          <Button
            htmlType="submit"
            type="primary"
            style={{ marginTop: 10 }}
            icon={<SearchOutlined />}
          >
            查询
          </Button>
        </Form.Item>

        <Form.Item>
          <Button type="default"  onClick={ onClear }  style={{ marginTop: 10 }}>
            清空
          </Button>
        </Form.Item>
      </Form>

      <Table columns={columns}
         dataSource={hospitalList}
        style={{marginTop:20}}
        bordered
        pagination={{
          total,
          current: page,
          pageSize,
          showQuickJumper: true,
          showSizeChanger: true,
          pageSizeOptions: ['2', '5', '10'],
          showTotal:(total)=>{ return `总共${total}条`},
          onChange:getHospitalList
          

        }}
        // loading={Loading}
      />
    </Card>
  );
}

export default HospitalList;
